package com.mioto.ld.communication.websocket;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.mioto.ld.communication.mqtt.protocol.model.Message;
import com.mioto.ld.communication.websocket.model.*;
import com.mioto.ld.communication.websocket.util.MessageSendUtil;
import com.mioto.ld.communication.websocket.util.WsChannelUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author mioto-qinxj
 * @date 2024/5/16
 * @desc
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class WebsocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        try {
            log.info("receive message - {} from websocket protocol",textWebSocketFrame.text());
            Gson gson = new GsonBuilder().registerTypeAdapter(WsMessageBody.class,new MessageBodyDeserializer(textWebSocketFrame.text())).create();
            WsRecMessage message = gson.fromJson(textWebSocketFrame.text(), WsRecMessage.class);
            //如果当前websocket连接没有存储到缓存中，并且该消息也不是认证指令，提示客户端必须认证
            if (ObjectUtil.notEqual(message.getCmd(), ReceiveCmdEnum.AUTH.cmd()) && !WsChannelUtil.isExist(channelHandlerContext)){
                MessageSendUtil.send(channelHandlerContext.channel(), SendCmdEnum.AUTH_REQUIRED);
                return;
            }
            ReceiveCmdEnum.getResolverByCmd(message.getCmd()).resolve(channelHandlerContext,message);
        }catch (Exception e){
            log.error("parse websocket message - {} fail",textWebSocketFrame.text(),e);
            MessageSendUtil.send(channelHandlerContext.channel(),SendCmdEnum.BAD_REQUEST);
        }
    }
}
